package com.liwei.easyweibo.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import android.content.Context;

import com.tencent.mm.algorithm.MD5;

public class ImageLoader {
	private String mImagePath ;
	private NotifiyOver mNotify;
	private Context 	mContext;
	
	public ImageLoader(String imagePath, NotifiyOver notify,Context context){
		mImagePath 	= imagePath;
		mNotify 			= notify;
		mContext		=context;
		new Thread(new DownloadRunnable()).start();;
	}
	
	public  class DownloadRunnable implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			String name = MD5.getMD5(mImagePath) + mImagePath.substring(mImagePath.lastIndexOf("."));
			String downloadPath = AndroidUtil.getPrimarySDCard();
			String filePathStr = downloadPath +Constant.SAVE_IMAGE_PATH+name;
			Util.writeToPreference(mContext, Constant.SHARE_ICON_PATH, filePathStr);
			File file = new File(filePathStr);
			try {
				URL url = new URL(mImagePath);
				HttpURLConnection conn  = (HttpURLConnection) url.openConnection();
				conn.setDoInput(true);
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5000);
				if(conn.getResponseCode() == 200){
					InputStream is = conn.getInputStream();
					FileOutputStream fos = new FileOutputStream(file);
					
					byte[] b = new byte[1024];
					int len = 0;
					while((len=is.read(b)) != -1){
						fos.write(b, 0, len);
					}
					mNotify.notifiysuccess(filePathStr);
					is.close();
					fos.close();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	public interface NotifiyOver{
		public void notifiysuccess(String downloadpath);
	}
}
